//============================================================================
// Name        : AnnotatedMethodVisitor.java
// Author      : iron.yin@gmail.com
// Version     : v1.0
// Copyright   : RisingSun CO,.LTD
// Description : AnnotatedMethodVisitor.java in Java
//============================================================================
package cc.risingsun.wing.core;

import java.lang.annotation.Annotation;
import java.util.Map;

import org.objectweb.asm.AnnotationVisitor;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;

import cc.risingsun.wing.core.generator.WingGeneratorUtil;
import cc.risingsun.wing.core.reflect.ReflectionHelper;

/**
 *
 *@author iron.yin@gmail.com
 */
public class AnnotatedMethodVisitor extends MethodVisitor implements Opcodes{
	
	protected String owner;
	protected boolean isAnnotated;
	final Map<String,Class<? extends Annotation>> annotations;
	WingMethod method;
	
	public AnnotatedMethodVisitor(Class<? extends Annotation>... annotations) {
		this(null,annotations);
	}
	
	public AnnotatedMethodVisitor(MethodVisitor mv,Class<? extends Annotation>... annotations){
		super(ASM4, mv);
		this.annotations = ReflectionHelper.getAnnotations(annotations);
		WingGeneratorUtil.registerMethodAnnotations(annotations);
	}
	
	void setASMMethod(WingMethod method){
		this.method=method;
	}
	
	@Override
	public AnnotationVisitor visitAnnotation(String desc, boolean visible) {
		if(annotations==null||!annotations.containsKey(desc)){
			return null;
		}
		return new AnnotationVisitorHolder(method.createAnnotation(method.getName(),desc,annotations.get(desc)), super.visitAnnotation(desc, visible));
	}
	
	@Override
	public AnnotationVisitor visitParameterAnnotation(int parameter,
			String desc, boolean visible) {
		if(annotations!=null&&!annotations.containsKey(desc)){
			return null;
		}
		WingParameter param = method.getParams()[parameter];
		return new AnnotationVisitorHolder(param.createAnnotation(param.getName(),desc,annotations.get(desc)), super.visitParameterAnnotation(parameter, desc, visible));
	}
}
